<script setup>
import ChannelSelect from './ChannelSelect.vue'
import { nextTick, ref } from 'vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { Plus } from '@element-plus/icons-vue'
import 'element-plus/dist/index.css'
import {
  ArticleAddService,
  ArticleGetProfileService,
  ArticleUpdateService
} from '@/api/article'
// 请求参数列表
const articleAddForm = ref({
  title: '',
  cate_id: '',
  content: '',
  cover_img: '',
  state: '',
  id: -1
})
// 表单校验
const articleAddFormRules = {
  title: [
    { required: true, message: '文章标题不能为空', trigger: 'blur' },
    { pattern: /^\S{1,30}$/, message: '任意1-30个非空字符', trigger: 'blur' }
  ],
  cate_id: [{ required: true, message: '文章分类不能为空', trigger: 'blur' }],
  cover_img: [{ required: true, message: '上传图片不能为空', trigger: 'blur' }],
  content: [{ required: true, message: '文章内容不能为空', trigger: 'blur' }]
}
// 获取文章详情回显
import { baseURL } from '@/utils/request'
// import axios from 'axios'
const getArticleProfile = async (id) => {
  const res = await ArticleGetProfileService(id)
  const data = res.data
  articleAddForm.value.title = data.title
  articleAddForm.value.cate_id = data.cate_id
  articleAddForm.value.content = data.content
  imageUrl.value = baseURL + data.cover_img
  // imageUrlToFile(imageUrl.value, 'image.jpg').then((file) => {
  //   articleAddForm.value.cover_img = file
  // })
  fetchImageAsFile(imageUrl.value, 'image.jpg').then((file) => {
    articleAddForm.value.cover_img = file
  })
  articleAddForm.value.id = id
  articleAddForm.value.state = data.state
  // console.log(articleAddForm.value)
}
// 控制展开暴露的方法
const editRef = ref(null)
const articleAddFormRef = ref(null)
const title = ref('')
const isVisiable = ref(false)
const open = async (row) => {
  isVisiable.value = true
  await nextTick()
  articleAddFormRef.value.resetFields()
  editRef.value.setHTML('')
  articleAddForm.value.state = ''
  articleAddForm.value.id = -1
  imageUrl.value = ''
  if (!row.id) {
    title.value = '添加文章'
  } else {
    // console.log(row)
    title.value = '编辑文章'
    getArticleProfile(row.id)
  }
}
defineExpose({ open })
// 文件上传，将file对象转化为url形式
const imageUrl = ref('')
const handleUploadPic = (uploadFile) => {
  // console.log(uploadFile)
  articleAddForm.value.cover_img = uploadFile.raw
  imageUrl.value = URL.createObjectURL(uploadFile.raw)
}
// 将url形式的转化为file对象(法二，使用fetch)
async function fetchImageAsFile(imageUrl, fileName) {
  try {
    const response = await fetch(imageUrl)
    if (!response.ok) {
      throw new Error('图片抓取失败')
    }
    const imageBlob = await response.blob()
    const imageFile = new File([imageBlob], fileName, { type: imageBlob.type })
    // 返回一个包含 File 对象和 uid 的自定义对象
    return imageFile
  } catch (error) {
    throw new Error(error)
  }
}
// 将网络图片地址转换为File对象(使用hm的方法)
// async function imageUrlToFile(url, fileName) {
//   try {
//     // 第一步：使用axios获取网络图片数据
//     const response = await axios.get(url, { responseType: 'arraybuffer' })
//     const imageData = response.data

//     // 第二步：将图片数据转换为Blob对象
//     const blob = new Blob([imageData], {
//       type: response.headers['content-type']
//     })

//     // 第三步：创建一个新的File对象
//     const file = new File([blob], fileName, { type: blob.type })

//     return file
//   } catch (error) {
//     console.error('将图片转换为File对象时发生错误:', error)
//     throw error
//   }
// }
// 添加文章或更新文章
const res = ref('')
const emit = defineEmits(['showSuccess'])
const handleAdd = async (state) => {
  articleAddForm.value.state = state
  const formdata = new FormData()
  console.log(articleAddForm.value)
  for (let key in articleAddForm.value) {
    formdata.append(key, articleAddForm.value[key])
  }
  if (articleAddForm.value.id === -1) {
    res.value = await ArticleAddService(formdata)
    emit('showSuccess', { message: res.value.message, type: 'add' })
  } else {
    res.value = await ArticleUpdateService(formdata)
    emit('showSuccess', { message: res.value.message, type: 'edit' })
  }
  isVisiable.value = false
}
</script>
<template>
  <div class="article-drawer">
    <el-drawer v-model="isVisiable" size="40%">
      <template #header>
        <h3>{{ title }}</h3>
      </template>
      <template #default>
        <el-form
          :model="articleAddForm"
          :rules="articleAddFormRules"
          ref="articleAddFormRef"
        >
          <el-form-item label="文章标题" prop="title">
            <el-input
              v-model="articleAddForm.title"
              placeholder="请输入文章标题"
            ></el-input>
          </el-form-item>
          <el-form-item label="文章分类" prop="cate_id" class="item2">
            <channel-select
              channel-width="100%"
              v-model:cateId="articleAddForm.cate_id"
            ></channel-select>
          </el-form-item>
          <el-form-item label="文章封面" prop="cover_img">
            <el-upload
              class="avatar-uploader"
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleUploadPic"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="文章内容" prop="content" class="item4">
            <quill-editor
              theme="snow"
              v-model:content="articleAddForm.content"
              contentType="html"
              ref="editRef"
            ></quill-editor
          ></el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button type="primary" @click="handleAdd('已发布')"
            >发布</el-button
          >
          <el-button type="info" @click="handleAdd('草稿')">草稿</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>
<style lang="scss" scoped>
.article-drawer {
  .el-form {
    width: 100%;
    height: 100%;
    // background: green;
    .avatar-uploader {
      .avatar {
        display: block;
      }
      :deep(.el-upload) {
        width: 300px;
        height: 300px;
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
        img {
          height: 300px;
          width: 300px;
          object-fit: cover; /* 图片居中裁剪，填满容器（不拉伸） */
        }
      }
      :deep(.el-upload:hover) {
        border-color: var(--el-color-primary);
      }
      .el-icon.avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        text-align: center;
      }
    }
    .item2 {
      .el-form-item__content div {
        width: 100%;
      }
    }
    .item4 {
      :deep(.ql-toolbar) {
        width: 100%;
      }
      :deep(.ql-container) {
        width: 100%;
        height: 500px;
      }
    }
  }
}
</style>
